package www13;

//饿汉式单例模式
class SingletonEager {
 private static final SingletonEager INSTANCE = new SingletonEager();

 private SingletonEager() {}

 public static SingletonEager getInstance() {
     return INSTANCE;
 }
}

//懒汉式单例模式（线程不安全）
class SingletonLazyUnsafe {
 private static SingletonLazyUnsafe instance;

 private SingletonLazyUnsafe() {}

 public static SingletonLazyUnsafe getInstance() {
     if (instance == null) {
         instance = new SingletonLazyUnsafe();
     }
     return instance;
 }
}

//懒汉式单例模式（线程安全，方法同步）
class SingletonLazySafeSynchronized {
 private static SingletonLazySafeSynchronized instance;

 private SingletonLazySafeSynchronized() {}

 public static synchronized SingletonLazySafeSynchronized getInstance() {
     if (instance == null) {
         instance = new SingletonLazySafeSynchronized();
     }
     return instance;
 }
}

//双重检查锁定（Double-Checked Locking）单例模式
class SingletonDoubleCheckedLocking {
 private static volatile SingletonDoubleCheckedLocking instance;

 private SingletonDoubleCheckedLocking() {}

 public static SingletonDoubleCheckedLocking getInstance() {
     if (instance == null) {
         synchronized (SingletonDoubleCheckedLocking.class) {
             if (instance == null) {
                 instance = new SingletonDoubleCheckedLocking();
             }
         }
     }
     return instance;
 }
}

//静态内部类式单例模式
class SingletonHolder {
 private SingletonHolder() {}

 private static class SingletonHelper {
     private static final SingletonHolder INSTANCE = new SingletonHolder();
 }

 public static SingletonHolder getInstance() {
     return SingletonHelper.INSTANCE;
 }
}

//枚举式单例模式
enum SingletonEnum {
 INSTANCE;

 public void doSomething() {
     System.out.println("Enum Singleton is working!");
 }
}

//测试类
public class Main {
 public static void main(String[] args) {
     // 测试饿汉式单例
     SingletonEager eager = SingletonEager.getInstance();
     System.out.println(eager);

     // 测试懒汉式单例（线程不安全，不推荐在实际使用）
     SingletonLazyUnsafe lazyUnsafe = SingletonLazyUnsafe.getInstance();
     System.out.println(lazyUnsafe);

     // 测试懒汉式单例（线程安全，方法同步，但性能较差）
     SingletonLazySafeSynchronized lazySafeSynchronized = SingletonLazySafeSynchronized.getInstance();
     System.out.println(lazySafeSynchronized);

     // 测试双重检查锁定单例
     SingletonDoubleCheckedLocking doubleChecked = SingletonDoubleCheckedLocking.getInstance();
     System.out.println(doubleChecked);

     // 测试静态内部类式单例
     SingletonHolder holder = SingletonHolder.getInstance();
     System.out.println(holder);

     // 测试枚举式单例
     SingletonEnum enumSingleton = SingletonEnum.INSTANCE;
     enumSingleton.doSomething();
 }
}